using System;
using System.Linq;
using System.Linq.Expressions;

namespace Comteck.Ktt.Services {
  /// <summary>
  /// 
  /// </summary>
  public static class QueryableExtensions {
    /// <summary>
    /// 扩展的 WhereIf 查询内部实现，可替换 if (condition) { source = source.Where(predicate); }
    /// </summary>
    /// <typeparam name="TSource"></typeparam>
    /// <param name="source"></param>
    /// <param name="condition"></param>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public static IQueryable<TSource> WhereIIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate) {
      return condition ? source.Where(predicate) : source;
    }

    /// <summary>
    /// 扩展的 WhereIf 查询内部实现，可替换 if (condition) { source = source.Where(predicateTrue); } else { source = source.Where(predicateFalse); }
    /// </summary>
    /// <typeparam name="TSource"></typeparam>
    /// <param name="source"></param>
    /// <param name="condition"></param>
    /// <param name="predicateTrue"></param>
    /// <param name="predicateFalse"></param>
    /// <returns></returns>
    public static IQueryable<TSource> WhereIIf<TSource>(this IQueryable<TSource> source, bool condition,
      Expression<Func<TSource, bool>> predicateTrue, Expression<Func<TSource, bool>> predicateFalse) {
      return condition ? source.Where(predicateTrue) : source.Where(predicateFalse);
    }

    /// <summary>
    /// 扩展的 WhereIf 查询内部实现，可替换 if (condition) { source = source.Where(predicate); }
    /// </summary>
    /// <typeparam name="TSource"></typeparam>
    /// <param name="source"></param>
    /// <param name="condition"></param>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public static IQueryable<TSource> WhereIIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, int, bool>> predicate) {
      return condition ? source.Where(predicate) : source;
    }

    /// <summary>
    /// 扩展的 WhereIf 查询内部实现，可替换 if (condition) { source = source.Where(predicateTrue); } else { source = source.Where(predicateFalse); }
    /// </summary>
    /// <typeparam name="TSource"></typeparam>
    /// <param name="source"></param>
    /// <param name="condition"></param>
    /// <param name="predicateTrue"></param>
    /// <param name="predicateFalse"></param>
    /// <returns></returns>
    public static IQueryable<TSource> WhereIIf<TSource>(this IQueryable<TSource> source, bool condition,
      Expression<Func<TSource, int, bool>> predicateTrue, Expression<Func<TSource, int, bool>> predicateFalse) {
      return condition ? source.Where(predicateTrue) : source.Where(predicateFalse);
    }
  }
}
